using System.Collections;
using Cysharp.Threading.Tasks;
using UniFramework.Event;
using UnityEngine;
using UnityEngine.SceneManagement;
using YooAsset;

namespace YPFramework
{
    public class YooAssetsModule : AssetsModule
    {
        /// <summary>
        /// 资源系统运行模式
        /// </summary>
        public EPlayMode PlayMode = EPlayMode.EditorSimulateMode;

        // 资源包对象
        private ResourcePackage _package;

        // 加载UI
        private GameObject _loadingUI;

        public override void Initialized()
        {
            Debug.Log($"资源系统运行模式：{PlayMode}");

            // 初始化事件系统
            UniEvent.Initalize();

            // 初始化资源系统
            YooAssets.Initialize();

            // 加载更新页面
            var go = Resources.Load<GameObject>("PatchWindow");
            _loadingUI = GameObject.Instantiate(go);

            // 创建默认的资源包
            _package = YooAssets.CreatePackage("DefaultPackage");
            // 设置该资源包为默认的资源包，可以使用YooAssets相关加载接口加载该资源包内容。
            YooAssets.SetDefaultPackage(_package);
            StartCoroutine(InitPackage());
        }

        private IEnumerator InitPackage()
        {
            // 开始补丁更新流程
            PatchOperation operation = new PatchOperation("DefaultPackage",
                EDefaultBuildPipeline.BuiltinBuildPipeline.ToString(), PlayMode);
            YooAssets.StartOperation(operation);
            yield return operation;

            Debug.Log("YPBox初始化完成");
            Entry.OnFrameworkInitCompelete?.Invoke();
            Destroy(_loadingUI);
        }

        public override async UniTask<T> LoadAssetAsync<T>(string location)
        {
            AssetHandle handle = _package.LoadAssetAsync<T>(location);
            await handle.ToUniTask();
            return handle.AssetObject as T;
        }

        public override async UniTask LoadSceneAsync(string location, LoadSceneMode sceneMode)
        {
            var physicsMode = LocalPhysicsMode.None;
            bool suspendLoad = false;
            SceneHandle handle = _package.LoadSceneAsync(location, sceneMode, physicsMode, suspendLoad);
            await handle.ToUniTask();
        }

        public override async UniTask<T> LoadSubAssetsAsync<T>(string location)
        {
            SubAssetsHandle handle = _package.LoadSubAssetsAsync<T>(location);
            await handle.ToUniTask();
            return handle.GetSubAssetObject<T>(location);
        }

        public override void UnloadUnusedAssets()
        {
            _package.UnloadUnusedAssetsAsync().WaitForAsyncComplete();
        }
    }
}
